package com.winit.clQueue.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.winit.clQueue.mapper.ClQueueMapper;
import com.winit.clQueue.model.ClQueue;
import com.winit.clQueue.service.ClQueueService;
import com.winit.cloudlink.Cloudlink;
import com.winit.cloudlink.event.Event;
import com.winit.cloudlink.event.EventOperation;
import com.winit.cloudlink.message.Message;
import com.winit.common.base.bean.ExecuteResult;
import com.winit.commons.util.SeqGenerate;
import com.winit.config.model.Config;
import com.winit.config.service.IConfigService;
import com.winit.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanglin on 2018/6/4.
 */
@Service
public class ClQueueServiceImpl implements ClQueueService {
    @Autowired
    ClQueueMapper clQueueMapper;
    @Autowired
    IConfigService configService;

    @Resource
    private Cloudlink cloudlink;

    @Autowired
    RedisService redisService;

    @Override
    public ClQueue findNameAndAppId(String name, String appId,String type){
        Map selectMap=new HashMap<>();
        selectMap.put("name",name);
        selectMap.put("appId",appId);
        selectMap.put("type",type);
        return clQueueMapper.findNameAndAppId(selectMap);
    }

    @Override
    public ExecuteResult saveClQueue(ClQueue clQueue) {
        ExecuteResult er =new ExecuteResult();
        if(StringUtils.isEmpty(clQueue.getId())){
            clQueue.setId(SeqGenerate.createId("CLQU"));
        }
        try {
            clQueueMapper.insertSelective(clQueue);
        }catch (Exception e){
            er.setDesc("保存失败，请联系beetle管理员");
            er.setCode("1");
            return er;
        }
        er.setData(clQueue);
        return er;
    }

    @Override
    public ExecuteResult getApps(String country, String zone, String type) {
        ExecuteResult er=new ExecuteResult();
        Map selectMap=new HashMap<>();
        if(!StringUtils.isEmpty(country) && !StringUtils.isEmpty(zone)){
            selectMap.put("region",zone+"."+country);
        }else{
            selectMap.put("zone",zone);
            selectMap.put("country",country);
        }
        selectMap.put("type",type);
        try {
            List<String> apps = clQueueMapper.getApps(selectMap);
            er.setData(apps);
        }catch (Exception e){
            er.setDesc(e.getMessage());
            er.setCode("1");
            return er;
        }
        return er;
    }

    @Override
    public ExecuteResult getClParam(String appId, String id,String isParam) {
        ExecuteResult er=new ExecuteResult();
        Map selectMap = new HashMap<>();
        selectMap.put("id",id);
        selectMap.put("appId",appId);
        List<ClQueue> clqueues = clQueueMapper.getClParams(selectMap);
        if("1".equals(isParam) && clqueues.size()>0){
            try {
                for(ClQueue clqueue: clqueues){
                    Config config = configService.getConfigMap(clqueue.getParamConfigId(), false);
                    clqueue.setParams(JSONObject.parseObject(config.getKVMap().get("param")));
                }
            } catch (Exception e) {
                er.setCode("1");
                er.setDesc("查询异常，请联系Beetle管理员");
                e.printStackTrace();
                return er;
            }
        }
        er.setData(clqueues);
        return er;
    }

    @Override
    public ExecuteResult cloudLinkSend(JSONObject jsonObject) {
        ExecuteResult er =new ExecuteResult();
        String type = jsonObject.getString("type");
        String appId     = jsonObject.getString("appId");
        String  EventName = jsonObject.getString("eventName");
        try {
            if("MSG".equals(type)){
                this.CloudlinkSendMsg(appId,EventName,jsonObject);
            }else{
                this.CloudlinkSendEvent(EventName,jsonObject);
            }
        }catch (Exception e){
            er.setDesc("消息发送异常，请联系beetle管理员");
        }

        return er;
    }


    private void CloudlinkSendMsg(String appId,String EventName,JSONObject jsonObject){
        Message<JSONObject> message =cloudlink.newMessageBuilder() .direct(appId,EventName,  JSONObject.parse(jsonObject.getString("parameter"))).build();
        redisService.setObj(message.getHeaders().getMessageId(),jsonObject);
        cloudlink.sendMessage(message);
    }

    private void CloudlinkSendEvent(String EventName,JSONObject jsonObject){
        Event sendEvent = cloudlink.newEventBuilder().eventType(EventName)
                .eventOperation(EventOperation.Create)
                .module(jsonObject.getString("appType"))
                .payload(JSONObject.parse(jsonObject.getString("parameter"))).build();
        redisService.setObj(sendEvent.getHeaders().getEventId(),jsonObject);
        cloudlink.publishEvent(sendEvent);

    }

}
